package com.fingard.dsp.bank.directbank.pab01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Parker on 2019/7/16.
 * @version 1.0
 */
public class PAB01SyncTask extends PAB01Base {
    private ReqQryReceipt p_reqReceipt;
    private PAB01Receipt pab01Receipt;

    public PAB01SyncTask(ReqQryReceipt p_reqReceipt, PAB01Receipt pab01Receipt) {
        this.p_reqReceipt = p_reqReceipt;
        this.pab01Receipt = pab01Receipt;
    }

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    public void downloadReceipt() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                StringBuilder logSb = new StringBuilder();
                try {
                    Calendar tmpCalendarFrom = Calendar.getInstance();
                    tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
                    setSbLog(logSb);
                    Calendar tmpCalendarTo = Calendar.getInstance();
                    tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

                    int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                    StringBuilder json = new StringBuilder();
                    if (pab01Receipt.getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                        json.append("tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[");
                    } else {
                        json.append("transType=downloadreceipt&data={\"rows\":[");
                    }
                    int tmpFileCount = 0;//上传回单数量
                    //按日循环
                    while (tmpIntFrom <= tmpIntTo) {//按日查询
                        //定义存储回单信息的billNo-value集合
                        Map<String, Map<String, String>> billContentMap = new HashMap<String, Map<String, String>>();
                        //获取回单信息
                        PAB01Header bankHeader = new PAB01Header();
                        int intFromStep = tmpIntFrom;
                        Date fromDateStep = tmpCalendarFrom.getTime();
                        WriteBankLogLn("执行" + intFromStep + "的回单数据查询");
                        XmlTextWriter resultWriter = new XmlTextWriter();
                        resultWriter.writeStartElement("Result");
                        bankHeader.trncode = "ELC001";
                        bankHeader.fourZero = "0000";

                        int recordNum = pab01Receipt.getBankConfig().getValueAsInt("recordNum", 200, "receipt");//每页记录数
                        int startRecord = 1;//起始值为1，不能送0

                        String respCode = "";
                        String respInfo = "";
                        String endFlag = "N";//Y:无剩余记录  N:有剩余记录
                        boolean tmpQryNext = true;
                        while (tmpQryNext && respCode.length() == 0 && !"Y".equals(endFlag)) {//分页查询

                            XmlTextWriter xmlWriter = new XmlTextWriter();
                            xmlWriter.autoFormat = false;
                            pab01Receipt.writeCommonHeader(xmlWriter);
                            xmlWriter.writeStartElement("Result");
                            xmlWriter.writeElementString("AcctNo", p_reqReceipt.actNum);
                            xmlWriter.writeElementString("ReceiptType", "ALL");//回单类型
                            xmlWriter.writeElementString("SubType", "ALL");//子类型
                            xmlWriter.writeElementString("StartDate", Format.Date8Format.format(fromDateStep));//起始日期 格式yyyyMMdd（记账日期）
                            xmlWriter.writeElementString("EndDate", Format.Date8Format.format(fromDateStep));//结束日期
                            xmlWriter.writeElementString("StartRecord", startRecord + "");//起始值为1，不能送0
                            xmlWriter.writeElementString("RecordNum", recordNum + "");//本批记录数
                            xmlWriter.writeElementClosed("StartAmt");//非必输，开始金额
                            xmlWriter.writeElementClosed("EntAmt");//非必输，结束金额
                            /*001：交易时间从近到远   002：交易时间从远到近   003：金额升序（从小到大）   004：金额降序（从大到小）   005：回单号升序   006：回单号降序*/
                            xmlWriter.writeElementClosed("OrderMode");//非必输，排序方式
                            xmlWriter.writeElementClosed("PayeeAcctNo");//非必输，收款人账号
                            xmlWriter.writeElementClosed("PayeeName");//非必输，收款人名称
                            xmlWriter.writeElementClosed("DrCrFlag");//非必输，借贷标志
                            xmlWriter.writeElementClosed("Ccy");//非必输，币种
                            xmlWriter.writeElementClosed("SerialNo");//非必输，顺序号
                            xmlWriter.writeElementClosed("PrintBranchId");//非必输，打印网点
                            xmlWriter.writeElementClosed("ReceiptNo");//非必输，回单号
                            xmlWriter.writeElementClosed("PrintFlag");//非必输，打印标志，0：首次打印      1：补打
                            xmlWriter.writeEndDocument();
                            bankHeader.reqSeqNo = getQryTransID();
                            WriteBankLogLn("发送银行报文:\r\n:" + xmlWriter.toXmlString());
                            String[] tmpStrRet = pab01Receipt.sendToBank(xmlWriter.toXmlString(), bankHeader);
                            //String[] tmpStrRet = new String[]{"","A001010101009010400000000590000000004421ELC001     0220190821152919190821152919002     000000:交易受理成功                                                                                       00000                       0<?xml version=\"1.0\" encoding=\"GBK\" ?><Result><RecordTotalCount>2</RecordTotalCount><StartRecord>1</StartRecord><ResultNum>500</ResultNum><EndFlag>Y</EndFlag><list><ReceiptNo>19081504180010000002</ReceiptNo><CheckCode>703947</CheckCode><ReceiptType>001</ReceiptType><SubType>000</SubType><BookingDate>20190815</BookingDate><PayerName>金科地产集团股份有限公司</PayerName><PayeeName>杭州金唐房地产开发有限公司</PayeeName><PayerAccNo>15000019943739</PayerAccNo><PayeeAccNo>19005101040033137</PayeeAccNo><PayerAcctOpenBranchID>0418</PayerAcctOpenBranchID><PayeeAcctOpenBranchID>103331000517</PayeeAcctOpenBranchID><PayerAcctOpenBranchName>平安银行重庆新牌坊支行</PayerAcctOpenBranchName><PayeeAcctOpenBranchName>中国农业银行杭州市中山支行营业中心</PayeeAcctOpenBranchName><MainAcctNo>15000019943739</MainAcctNo><SubAcctNo></SubAcctNo><OldAcctNo></OldAcctNo><Ccy>RMB</Ccy><TranAmt>100000000.0000</TranAmt><SubBranchID>0418</SubBranchID><DrCrFlag>D</DrCrFlag><Crpp>往来款(网银)</Crpp><Corpus>0.0000</Corpus><DepositIntRate>0.0000000</DepositIntRate><DepositReceiptNo></DepositReceiptNo><StartPeriod></StartPeriod><EndPeriod></EndPeriod><InterestTax>0.0000000</InterestTax><IntInterest>0.00</IntInterest><OverdraftInterest>0.0000</OverdraftInterest><TaxRate>0.0000000</TaxRate><LoanAcctNo></LoanAcctNo><DuebillNo></DuebillNo><PaidAmt>0.0000</PaidAmt><RepayCorpus>0.0000</RepayCorpus><ReplyInterest>0.0000</ReplyInterest><ComInterest>0.0000</ComInterest><CorpusBalance>0.0000</CorpusBalance><DueRepayCorpus>0.0000</DueRepayCorpus><RepayCount>0</RepayCount><Commission>0.0000</Commission><MaterialFee>0.0000</MaterialFee><TaxedInterest>0.0000</TaxedInterest><HostSeqNo>3240791908155600154488</HostSeqNo><LoanIntRate>0.0000000</LoanIntRate><ReceivableInterest>0.0000</ReceivableInterest><TellerNo>EB001</TellerNo><AuthTellerNo>0000</AuthTellerNo><PrintClientName>网银</PrintClientName><PrintTime>201908211508935</PrintTime><PrintTimes>2</PrintTimes><RegionNo>0000</RegionNo><TermNo></TermNo><PrintNote>9998</PrintNote><BussType></BussType><IntSettleAcctNo></IntSettleAcctNo><AcctOpenBranchID>0418</AcctOpenBranchID><TranDate>20190815</TranDate><TranTime>100904</TranTime><BranchId>0418</BranchId><SerialNo>1</SerialNo><RecordType></RecordType><FrontEndCode>218540</FrontEndCode><RemarkCode>WEB</RemarkCode><Summary>网银</Summary></list><list><ReceiptNo>19081504180080000004</ReceiptNo><CheckCode>137617</CheckCode><ReceiptType>008</ReceiptType><SubType>000</SubType><BookingDate>20190815</BookingDate><PayerName>金科地产集团股份有限公司</PayerName><PayeeName></PayeeName><PayerAccNo>15000019943739</PayerAccNo><PayeeAccNo></PayeeAccNo><PayerAcctOpenBranchID>0418</PayerAcctOpenBranchID><PayeeAcctOpenBranchID></PayeeAcctOpenBranchID><PayerAcctOpenBranchName>平安银行重庆新牌坊支行</PayerAcctOpenBranchName><PayeeAcctOpenBranchName></PayeeAcctOpenBranchName><MainAcctNo>15000019943739</MainAcctNo><SubAcctNo></SubAcctNo><OldAcctNo></OldAcctNo><Ccy>RMB</Ccy><TranAmt>200.0000</TranAmt><SubBranchID>0418</SubBranchID><DrCrFlag>D</DrCrFlag><Crpp>企业网银异地跨行汇款（加急）</Crpp><Corpus>0.0000</Corpus><DepositIntRate>0.0000000</DepositIntRate><DepositReceiptNo></DepositReceiptNo><StartPeriod></StartPeriod><EndPeriod></EndPeriod><InterestTax>0.0000000</InterestTax><IntInterest>0.00</IntInterest><OverdraftInterest>0.0000</OverdraftInterest><TaxRate>0.0000000</TaxRate><LoanAcctNo></LoanAcctNo><DuebillNo></DuebillNo><PaidAmt>0.0000</PaidAmt><RepayCorpus>0.0000</RepayCorpus><ReplyInterest>0.0000</ReplyInterest><ComInterest>0.0000</ComInterest><CorpusBalance>0.0000</CorpusBalance><DueRepayCorpus>0.0000</DueRepayCorpus><RepayCount>0</RepayCount><Commission>0.0000</Commission><MaterialFee>0.0000</MaterialFee><TaxedInterest>0.0000</TaxedInterest><HostSeqNo>3240791908155600154488</HostSeqNo><LoanIntRate>0.0000000</LoanIntRate><ReceivableInterest>0.0000</ReceivableInterest><TellerNo>EB001</TellerNo><AuthTellerNo>0000</AuthTellerNo><PrintClientName>网银</PrintClientName><PrintTime>201908211508936</PrintTime><PrintTimes>1</PrintTimes><RegionNo>0000</RegionNo><TermNo></TermNo><PrintNote>9998</PrintNote><BussType></BussType><IntSettleAcctNo></IntSettleAcctNo><AcctOpenBranchID>0418</AcctOpenBranchID><TranDate>20190815</TranDate><TranTime>100904</TranTime><BranchId></BranchId><SerialNo></SerialNo><RecordType></RecordType><FrontEndCode>218540</FrontEndCode><RemarkCode>5003</RemarkCode><Summary>手续费</Summary></list></Result>","000000","交易受理成功"};
                            WriteBankLogLn("银行返回结果:\r\n:" + Arrays.toString(tmpStrRet));
                            if (tmpStrRet[0].length() == 0 && StringHelper.hasAnyChar(tmpStrRet[1])) {
                                String retCode = tmpStrRet[2];
                                String retInfo = tmpStrRet[3];
                                if ("000000".equals(retCode)) {
                                    if (tmpStrRet[1].contains("<")) {
                                        StringBuilder tmpSbMsg = new StringBuilder();
                                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);

                                        if (tmpBkReader != null) {
                                            //Y:无剩余记录  N:有剩余记录
                                            endFlag = tmpBkReader.getFirstText("/Result/EndFlag").toUpperCase();
                                            int totalCount = 0;
                                            String rdTotalCount = tmpBkReader.getFirstText("/Result/RecordTotalCount");//记录总数
                                            if (StringHelper.hasAnyChar(rdTotalCount)) {
                                                totalCount = Integer.parseInt(rdTotalCount);
                                            }

                                            if (totalCount <= 0) {
                                                tmpQryNext = false;
                                                respCode = "-1";
                                                respInfo = "记录总数为0";
                                            } else {
                                                int cmpStartRecord = 0;
                                                String bkStartRecord = tmpBkReader.getFirstText("/Result/StartRecord");//起始记录数
                                                if (StringHelper.hasAnyChar(bkStartRecord)) {
                                                    cmpStartRecord = Integer.parseInt(bkStartRecord);
                                                }
                                                if (cmpStartRecord != startRecord) {
                                                    tmpQryNext = false;
                                                    respCode = "-1";
                                                    respInfo = "响应起始记录数" + bkStartRecord + "与请求" + startRecord + "不一致";
                                                } else {
                                                    int addResultNum = 0;
                                                    String bkResultNum = tmpBkReader.getFirstText("/Result/ResultNum");//本次返回记录数
                                                    if (StringHelper.hasAnyChar(bkResultNum)) {
                                                        addResultNum = Integer.parseInt(bkResultNum);
                                                    }
                                                    if (addResultNum > 0) {
                                                        startRecord += addResultNum;//继续查询

                                                        while (tmpBkReader.read("/Result/list")) {

                                                            resultWriter.writeXElement(tmpBkReader.readedXElement);
                                                            Map<String, String> tmpMap = new HashMap<String, String>();
                                                            String billNo = tmpBkReader.readedXElement.getSingleText("ReceiptNo");
                                                            tmpMap.put("receiptCode", billNo);
                                                            tmpMap.put("receiptType", tmpBkReader.readedXElement.getSingleText("ReceiptType"));
                                                            tmpMap.put("PayeeAccNo", tmpBkReader.readedXElement.getSingleText("PayeeAccNo"));
                                                            tmpMap.put("PayerName", tmpBkReader.readedXElement.getSingleText("PayerName"));
                                                            tmpMap.put("PayerAccNo", tmpBkReader.readedXElement.getSingleText("PayerAccNo"));
                                                            tmpMap.put("PayeeName", tmpBkReader.readedXElement.getSingleText("PayeeName"));
                                                            tmpMap.put("TranAmt", tmpBkReader.readedXElement.getSingleText("TranAmt"));
                                                            tmpMap.put("HostSeqNo", tmpBkReader.readedXElement.getSingleText("HostSeqNo"));//主机流水号
                                                            tmpMap.put("RemarkCode", tmpBkReader.readedXElement.getSingleText("RemarkCode"));//摘要
                                                            billContentMap.put(billNo, tmpMap);
                                                        }

                                                    } else {
                                                        tmpQryNext = false;
                                                        respCode = "-1";
                                                        respInfo = "本次返回记录数为" + bkResultNum;
                                                    }
                                                }
                                            }
                                        } else {
                                            respCode = "-1";
                                            respInfo = tmpSbMsg.toString();
                                        }
                                    } else {
                                        respCode = "-1";
                                        respInfo = "银行返回报文格式非法";
                                    }
                                } else {
                                    respCode = "-1";
                                    respInfo = retInfo;
                                }
                            } else {
                                respCode = "-1";
                                respInfo = tmpStrRet[1];
                                if (StringHelper.isNullOrEmpty(respInfo)) {
                                    respInfo = "银行响应内容为空";
                                }
                                break;
                            }
                        }
                        if (respCode.length() == 0) {
                            resultWriter.writeEndDocument();
                            bankHeader = new PAB01Header();
                            bankHeader.trncode = pab01Receipt.getBankConfig().getValueAsString("receiptTransCode", "ELC002");
                            bankHeader.fourZero = "0000";
                            bankHeader.reqSeqNo = getQryTransID();
                            XmlTextWriter xmlWriter = new XmlTextWriter();
                            xmlWriter.autoFormat = false;
                            pab01Receipt.writeCommonHeader(xmlWriter);
                            xmlWriter.writeStartElement("Result");
                            xmlWriter.writeElementString("Account", p_reqReceipt.actNum);
                            xmlWriter.writeElementString("QueryDate", Format.Date8Format.format(fromDateStep));
                            //xmlWriter.writeElementString("BsnCode", "");
                            xmlWriter.writeEndDocument();

                            WriteBankLogLn("发送银行报文:\r\n:" + xmlWriter.toXmlString());
                            String[] tmpStrRet = pab01Receipt.sendToBank(xmlWriter.toXmlString(), bankHeader);
                            WriteBankLogLn("银行返回结果:\r\n:" + Arrays.toString(tmpStrRet));
                            /*String[] tmpStrRet = new String[]{"","<?xml version=\"1.0\" encoding=\"GBK\" ?>\n" +
                                    "<Result>\n" +
                                    "\t<list>\n" +
                                    "\t\t<FileName>11014632005006_4004_20170822.txt</FileName>\n" +
                                    "\t\t<FilePath></FilePath>\n" +
                                    "\t\t<RandomPwd>dHu4Nwj0Q44sIIxIebdL/PrxINlV/u7z</RandomPwd>\n" +
                                    "\t\t<SignData></SignData>\n" +
                                    "\t\t<HashData></HashData>\n" +
                                    "\t</list>\n" +
                                    "\t<list>\n" +
                                    "\t\t<FileName>11014632005006_4004_20170820.txt</FileName>\n" +
                                    "\t\t<FilePath></FilePath>\n" +
                                    "\t\t<RandomPwd>kra/vCiIECnFo5+y0vRuzo/21ROiY+kc</RandomPwd>\n" +
                                    "\t\t<SignData></SignData>\n" +
                                    "\t\t<HashData></HashData>\n" +
                                    "\t</list>\n" +
                                    "</Result>\n","000000",""};*/
                            if (tmpStrRet[0].length() == 0 && StringHelper.hasAnyChar(tmpStrRet[1])) {
                                String retCode = tmpStrRet[2];
                                //String retInfo = tmpStrRet[3];
                                if ("000000".equals(retCode)) {
                                    if (tmpStrRet[1].contains("<")) {
                                        StringBuilder tmpSbMsg = new StringBuilder();
                                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
                                        if (tmpBkReader != null) {
                                            DownloadFile download = new DownloadFile(pab01Receipt.reqHeader, pab01Receipt.bankFront, pab01Receipt.sbLog);
                                            download.setLogFlushTime(logFlushTime);
                                            if ("ELC002".equals(bankHeader.trncode)) {
                                                while (tmpBkReader.read("/Result")) {
                                                    /**  <list>
                                                     <FileName>123.pdf</FileName>
                                                     <FilePath>
                                                     </FilePath>
                                                     <RandomPwd>BLVJ5dXM39lorcmw/puCquJ4UGY9GJ2j</RandomPwd>
                                                     <SignData>
                                                     </SignData>
                                                     <HashData>
                                                     </HashData>
                                                     </list>*/
                                                    DownFileReq req = new DownFileReq(tmpBkReader.readedXElement);
                                                    //req.filePath="/afe_ftp/00303079800000117000";
                                                    String localSavePath = pab01Receipt.getTempFileDirectory() + File.separator + intFromStep;
                                                    req.filePath = localSavePath;
                                                    //req.randomPwd = "09DePaDjo37uF0BP9jywfZHIj4m+wgSa";
                                                    //下载文件
                                                    DownFileResp resp = download.downFile(req);
                                                    if (resp.execResult) {
                                                        DataFileHelper dFileHelper = new DataFileHelper(pab01Receipt);
                                                        WriteBankLogLn("文件下载已完成，开始解压...");
                                                        WriteBankLogLn("解压至：[" + localSavePath + "]");
                                                        ZipHelper.unzipFile(localSavePath + File.separator + req.fileName, localSavePath);
                                                        WriteBankLogLn("文件解压已完成.");
                                                        File depressDir = new File(localSavePath);
                                                        String destPath = depressDir.getAbsolutePath();
                                                        String[] parentFile = FileHelper.listFiles(destPath);
                                                        for (String pfile : parentFile) {
                                                            String[] files = FileHelper.listFiles(destPath + File.separator + pfile);
                                                            if (files == null) {
                                                                WriteBankLogLn("解压后文件夹" + destPath + "下为空");
                                                                continue;
                                                            }
                                                            for (String file : files) {
                                                                String localRecipt = destPath + File.separator + pfile + File.separator + file;
                                                                if ((file.endsWith(".PDF") || file.endsWith(".pdf")) && file.startsWith(p_reqReceipt.actNum)) {
                                                                    String ftpFilePath = "";
                                                                    String AtsFilePath = "";
                                                                    int result = -1;
                                                                    String tmpByDate = Format.Date8Format.format(new Date());
                                                                    tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                                                            + pab01Receipt.reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                                                    if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                                                        if ("localhost".equals(SmbFileUtil.getUploadType())) {//上传到本地目录
                                                                            String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                                            WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                                            result = FileHelper.copyFile(localRecipt, shareDir + tmpByDate + file);
                                                                            AtsFilePath = tmpByDate + file;//回单文件仓库存储路径
                                                                        } else {//上传到共享文件夹
                                                                            if (new File(localRecipt).exists()) {
                                                                                WriteBankLogLn(
                                                                                        "正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                                                result = SmbFileUtil.smbUploading(localRecipt, tmpByDate,
                                                                                        FGBiz.dspCenter.dspSet.receiptShareDir);
                                                                                AtsFilePath = tmpByDate + new File(localRecipt).getName();//回单文件仓库存储路径
                                                                            }
                                                                        }
                                                                    } else {
                                                                        //ftp服务器
                                                                        FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                                        WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                                                        AtsFilePath = tmpByDate + file;//回单文件仓库存储路径
                                                                        //上传ftp服务器的地址
                                                                        ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" + AtsFilePath;
                                                                        WriteBankLogLn("开始将回单" + localRecipt + "上传至" + ftpFilePath);
                                                                        //上传至ftp
                                                                        result = FtpUtil.ftpUploading(ftpSet3, localRecipt, ftpFilePath);
                                                                    }

                                                                    if (result == 0 || result == 1) {
                                                                        if (result == 0) {
                                                                            WriteBankLogLn("文件上传成功");
                                                                            tmpFileCount++;
                                                                        } else {
                                                                            WriteBankLogLn("文件已存在共享目录无需重复上传");
                                                                        }

                                                                        //String content = PdfGenerateUtil.readFileOfPDF(localRecipt);
                                                                        //String receiptCode = content.substring(content.indexOf("回单号：") + 4, content.indexOf("回单号：") + 24);

                                                                        String pdfContent = PdfGenerateUtil.getPdfFileText(localRecipt);//获取回单全部内容
                                                                        for (Map.Entry<String, Map<String, String>> entry : billContentMap.entrySet()) {
                                                                            if (pdfContent.contains(entry.getKey())) {//找出匹配回单编号的回单
                                                                                Map<String, String> tmpMap = entry.getValue();
                                                                                // 推送数据给ATS处理
                                                                                json.append("{");
                                                                                json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                                                                json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                                                                json.append("\"receiptCode\":\"" + tmpMap.get("receiptCode") + "\",");
                                                                                json.append("\"receiptType\":\"" + "" + "\",");
                                                                                json.append("\"receiptState\":\"" + "" + "\",");
                                                                                if (p_reqReceipt.actNum.equals(tmpMap.get("PayeeAccNo"))) {
                                                                                    json.append("\"oppActName\":\"" + tmpMap.get("PayerName") + "\",");
                                                                                    json.append("\"oppActNum\":\"" + tmpMap.get("PayerAccNo") + "\",");
                                                                                    json.append("\"moneyway\":\"" + "2" + "\",");
                                                                                } else {
                                                                                    json.append("\"oppActName\":\"" + tmpMap.get("PayeeName") + "\",");
                                                                                    json.append("\"oppActNum\":\"" + tmpMap.get("PayeeAccNo") + "\",");
                                                                                    json.append("\"moneyway\":\"" + "1" + "\",");
                                                                                }
                                                                                json.append("\"amount\":\"" + "" + tmpMap.get("TranAmt") + "\",");
                                                                        /*//回单数据：回单文件名第二个“_”后（流水号）、回单文件名第一个“_”后（日期）、回单文件名第五个“_”后（明细序号）
                                                                        if(file.split("_").length>5 && file.split("_")[5].toLowerCase().contains("pdf")){
                                                                            String tranSeqNo=file.split("_")[2]+file.split("_")[1]+file.split("_")[5];
                                                                            tranSeqNo=tranSeqNo.replace(".pdf","").replace(".PDF","");
                                                                            json.append("\"tranSeqNo\":\"" + tranSeqNo + "\",");
                                                                        }else {
                                                                            json.append("\"tranSeqNo\":\"" + "" + "\",");
                                                                        }*/
                                                                                json.append("\"tranSeqNo\":\"" + file.split("_")[2] + "\",");
                                                                                json.append("\"tranCode\":\"" + "" + "\",");
                                                                                json.append("\"tranDate\":\"" + Format.Date10Format.format(fromDateStep) + "\",");
                                                                                json.append("\"filePath\":\"" + AtsFilePath + "\",");
                                                                                json.append("\"fileType\":\"1\"");
                                                                                json.append("},");
                                                                            }
                                                                        }
                                                                /*Iterator<Map<String, String>> mapIterator = tmpResult.iterator();
                                                                while (mapIterator.hasNext()) {
                                                                    Map<String, String> tmpMap = mapIterator.next();
                                                                    if (file.split("_")[2].equals(tmpMap.get("HostSeqNo")) && file.split("_")[4].equals(tmpMap.get("RemarkCode"))) {
                                                                        // 推送数据给ATS处理
                                                                        json.append("{");
                                                                        json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                                                        json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                                                        json.append("\"receiptCode\":\"" + tmpMap.get("receiptCode") + "\",");
                                                                        json.append("\"receiptType\":\"" + "" + "\",");
                                                                        json.append("\"receiptState\":\"" + "" + "\",");
                                                                        if (p_reqReceipt.actNum.equals(tmpMap.get("PayeeAccNo"))) {
                                                                            json.append("\"oppActName\":\"" + tmpMap.get("PayerName") + "\",");
                                                                            json.append("\"oppActNum\":\"" + tmpMap.get("PayerAccNo") + "\",");
                                                                            json.append("\"moneyway\":\"" + "2" + "\",");
                                                                        } else {
                                                                            json.append("\"oppActName\":\"" + tmpMap.get("PayeeName") + "\",");
                                                                            json.append("\"oppActNum\":\"" + tmpMap.get("PayeeAccNo") + "\",");
                                                                            json.append("\"moneyway\":\"" + "1" + "\",");
                                                                        }
                                                                        json.append("\"amount\":\"" + "" + tmpMap.get("TranAmt") + "\",");
                                                                        回单数据：回单文件名第二个“_”后（流水号）、回单文件名第一个“_”后（日期）、回单文件名第五个“_”后（明细序号）
                                                                        if(file.split("_").length>5 && file.split("_")[5].toLowerCase().contains("pdf")){
                                                                            String tranSeqNo=file.split("_")[2]+file.split("_")[1]+file.split("_")[5];
                                                                            tranSeqNo=tranSeqNo.replace(".pdf","").replace(".PDF","");
                                                                            json.append("\"tranSeqNo\":\"" + tranSeqNo + "\",");
                                                                        }else {
                                                                            json.append("\"tranSeqNo\":\"" + "" + "\",");
                                                                        }
                                                                        json.append("\"tranSeqNo\":\"" + file.split("_")[2] + "\",");
                                                                        json.append("\"tranCode\":\"" + "" + "\",");
                                                                        json.append("\"tranDate\":\"" + Format.Date10Format.format(fromDateStep) + "\",");
                                                                        json.append("\"filePath\":\"" + AtsFilePath + "\",");
                                                                        json.append("\"fileType\":\"1\"");
                                                                        json.append("},");
                                                                        mapIterator.remove();
                                                                    }
                                                                }*/
                                                                    } else {
                                                                        WriteBankLogLn(intFromStep + ":上传文件至共享目录失败，请检查共享目录配置是否正确 ");
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    } else {
                                                        WriteBankLogLn("下载文件失败，路径" + req.filePath + "文件名" + req.fileName + "：" + resp.execMsg);
                                                    }
                                                }
                                            } else {//F00101
                                                while (tmpBkReader.read("/Result/list")) {
                                                    /**  <list>
                                                     <FileName>123.pdf</FileName>
                                                     <FilePath>
                                                     </FilePath>
                                                     <RandomPwd>BLVJ5dXM39lorcmw/puCquJ4UGY9GJ2j</RandomPwd>
                                                     <SignData>
                                                     </SignData>
                                                     <HashData>
                                                     </HashData>
                                                     </list>*/
                                                    DownFileReq req = new DownFileReq(tmpBkReader.readedXElement);
                                                    //req.filePath="/afe_ftp/00303079800000117000";
                                                    String localSavePath = pab01Receipt.getTempFileDirectory() + File.separator + intFromStep;
                                                    req.filePath = localSavePath;
                                                    //req.randomPwd = "09DePaDjo37uF0BP9jywfZHIj4m+wgSa";
                                                    //下载文件
                                                    DownFileResp resp = download.downFile(req);
                                                    if (resp.execResult) {
                                                        DataFileHelper dFileHelper = new DataFileHelper(pab01Receipt);
                                                        WriteBankLogLn("文件下载已完成，开始解压...");
                                                        WriteBankLogLn("解压至：[" + localSavePath + "]");
                                                        ZipHelper.unzipFile(localSavePath + File.separator + req.fileName, localSavePath);
                                                        WriteBankLogLn("文件解压已完成.");
                                                        File depressDir = new File(localSavePath);
                                                        String destPath = depressDir.getAbsolutePath();
                                                        String[] parentFile = FileHelper.listFiles(destPath);
                                                        for (String pfile : parentFile) {
                                                            String[] files = FileHelper.listFiles(destPath + File.separator + pfile);
                                                            if (files == null) {
                                                                WriteBankLogLn("解压后文件夹" + destPath + "下为空");
                                                                continue;
                                                            }
                                                            for (String file : files) {
                                                                String localRecipt = destPath + File.separator + pfile + File.separator + file;
                                                                if ((file.endsWith(".PDF") || file.endsWith(".pdf")) && file.startsWith(p_reqReceipt.actNum)) {
                                                                    String ftpFilePath = "";
                                                                    String AtsFilePath = "";
                                                                    int result = -1;
                                                                    String tmpByDate = Format.Date8Format.format(new Date());
                                                                    tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                                                            + pab01Receipt.reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                                                    if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                                                        if ("localhost".equals(SmbFileUtil.getUploadType())) {//上传到本地目录
                                                                            String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                                            WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                                            result = FileHelper.copyFile(localRecipt, shareDir + tmpByDate + file);
                                                                            AtsFilePath = tmpByDate + file;//回单文件仓库存储路径
                                                                        } else {//上传到共享文件夹
                                                                            if (new File(localRecipt).exists()) {
                                                                                WriteBankLogLn(
                                                                                        "正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                                                result = SmbFileUtil.smbUploading(localRecipt, tmpByDate,
                                                                                        FGBiz.dspCenter.dspSet.receiptShareDir);
                                                                                AtsFilePath = tmpByDate + new File(localRecipt).getName();//回单文件仓库存储路径
                                                                            }
                                                                        }
                                                                    } else {
                                                                        //ftp服务器
                                                                        FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                                        WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                                                        AtsFilePath = tmpByDate + file;//回单文件仓库存储路径
                                                                        //上传ftp服务器的地址
                                                                        ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" + AtsFilePath;
                                                                        WriteBankLogLn("开始将回单" + localRecipt + "上传至" + ftpFilePath);
                                                                        //上传至ftp
                                                                        result = FtpUtil.ftpUploading(ftpSet3, localRecipt, ftpFilePath);
                                                                    }

                                                                    if (result == 0 || result == 1) {
                                                                        if (result == 0) {
                                                                            WriteBankLogLn("文件上传成功");
                                                                            tmpFileCount++;
                                                                        } else {
                                                                            WriteBankLogLn("文件已存在共享目录无需重复上传");
                                                                        }

                                                                        //String content = PdfGenerateUtil.readFileOfPDF(localRecipt);
                                                                        //String receiptCode = content.substring(content.indexOf("回单号：") + 4, content.indexOf("回单号：") + 24);

                                                                        String pdfContent = PdfGenerateUtil.getPdfFileText(localRecipt);//获取回单全部内容
                                                                        for (Map.Entry<String, Map<String, String>> entry : billContentMap.entrySet()) {
                                                                            if (pdfContent.contains(entry.getKey())) {//找出匹配回单编号的回单
                                                                                Map<String, String> tmpMap = entry.getValue();
                                                                                // 推送数据给ATS处理
                                                                                json.append("{");
                                                                                json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                                                                json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                                                                json.append("\"receiptCode\":\"" + tmpMap.get("receiptCode") + "\",");
                                                                                json.append("\"receiptType\":\"" + "" + "\",");
                                                                                json.append("\"receiptState\":\"" + "" + "\",");
                                                                                if (p_reqReceipt.actNum.equals(tmpMap.get("PayeeAccNo"))) {
                                                                                    json.append("\"oppActName\":\"" + tmpMap.get("PayerName") + "\",");
                                                                                    json.append("\"oppActNum\":\"" + tmpMap.get("PayerAccNo") + "\",");
                                                                                    json.append("\"moneyway\":\"" + "2" + "\",");
                                                                                } else {
                                                                                    json.append("\"oppActName\":\"" + tmpMap.get("PayeeName") + "\",");
                                                                                    json.append("\"oppActNum\":\"" + tmpMap.get("PayeeAccNo") + "\",");
                                                                                    json.append("\"moneyway\":\"" + "1" + "\",");
                                                                                }
                                                                                json.append("\"amount\":\"" + "" + tmpMap.get("TranAmt") + "\",");
                                                                        /*//回单数据：回单文件名第二个“_”后（流水号）、回单文件名第一个“_”后（日期）、回单文件名第五个“_”后（明细序号）
                                                                        if(file.split("_").length>5 && file.split("_")[5].toLowerCase().contains("pdf")){
                                                                            String tranSeqNo=file.split("_")[2]+file.split("_")[1]+file.split("_")[5];
                                                                            tranSeqNo=tranSeqNo.replace(".pdf","").replace(".PDF","");
                                                                            json.append("\"tranSeqNo\":\"" + tranSeqNo + "\",");
                                                                        }else {
                                                                            json.append("\"tranSeqNo\":\"" + "" + "\",");
                                                                        }*/
                                                                                json.append("\"tranSeqNo\":\"" + file.split("_")[2] + "\",");
                                                                                json.append("\"tranCode\":\"" + "" + "\",");
                                                                                json.append("\"tranDate\":\"" + Format.Date10Format.format(fromDateStep) + "\",");
                                                                                json.append("\"filePath\":\"" + AtsFilePath + "\",");
                                                                                json.append("\"fileType\":\"1\"");
                                                                                json.append("},");
                                                                            }
                                                                        }
                                                                    } else {
                                                                        WriteBankLogLn(intFromStep + ":上传文件至共享目录失败，请检查共享目录配置是否正确 ");
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    } else {
                                                        WriteBankLogLn("下载文件失败，路径" + req.filePath + "文件名" + req.fileName + "：" + resp.execMsg);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            WriteBankLogLn("查询回单数据失败：" + respCode + "-" + respInfo);
                        }
                        tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                        tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                        //tmpResult.clear();
                    }
                    WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
                    json.append("]}");
                    if (tmpFileCount > 0) {
                        WriteBankLogLn("提交ATS的地址：" + FGBiz.dspCenter.dspSet.receiptPushServerUrl);
                        WriteBankLogLn("推送给ATS的数据" + json.toString());
                        String[] data = pab01Receipt.sendToATS(json.toString());
                        WriteBankLogLn("返回的数据" + data[1]);
                        if (data[0].length() == 0 && "ok".equals(data[1])) {
                            WriteBankLogLn("推送数据到ATS成功,请查看数据");
                        } else {
                            WriteBankLogLn("推送数据到ATS失败");
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    WriteBankLogLn(ex);
                } finally {
                    String tmpDateDir = Format.DateForLogFormat.format(new Date()).replace("-", File.separator);
                    String tmpSubFileName = FGBiz.dspCenter.bankLogsFirstDir + File.separator + tmpDateDir + File.separator + "PAB01" + File.separator + "SyncTask-downloadReceipt" + "_" + p_reqReceipt.actNum + "_" + Format.DateTime14Format.format(new Date()) + "_" + UUID.randomUUID() + ".txt";
                    String tmpLogFile = FGBiz.dspCenter.bankLogsDirPath + File.separator + tmpSubFileName;
                    try {
                        FileHelper.writeFile(tmpLogFile, logSb);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

            }
        });
        executorService.shutdown();
    }
}